#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:解压可迭代对象赋值给多个变量
问题: 如果一个可迭代对象的元素个数超过变量个数时，会抛出一个 ValueError 。 那么怎样才能从这个可迭代对象中解压出 N 个元素出来？
提示 : 
"""


def main():
    print('recipe1'.center(20,'*'))
    recipe1()
    print('recipe2'.center(20,'*'))
    recipe2()
    print('recipe3'.center(20,'*'))
    recipe3()
    print('recipe4'.center(20,'*'))
    recipe4()


def recipe1():
    '''分解'''
    record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
    print(f"{record = }")
    name, _, *phone_numbers = record
    print(f"{name = }")
    print(f"{phone_numbers = }")


def recipe2():
    '''星号表达式也能用在列表的开始部分'''
    nums = [10, 8, 7, 1, 9, 5, 10, 3]
    print(f"{nums = }")
    *trailing, current = nums
    print(f"{trailing = }")
    print(f"{current = }")


def recipe3():
    '''星号表达式在迭代元素为可变长元组的序列时是很有用的'''
    records = [
        ('foo', 1, 2),
        ('bar', 'hello'),
        ('foo', 3, 4),
    ]
    print(f"{records = }")
    for tag, *args in records:
        if tag == 'foo':
            do_foo(*args)
        elif tag == 'bar':
            do_bar(*args)


def recipe4():
    '''星号解压语法在字符串操作的时候也会很有用，比如字符串的分割'''
    line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
    print(f"{line = }")
    uname, *fields, homedir, sh = line.split(':')
    print(f"{uname = }")
    print(f"{homedir = }")
    print(f"{sh = }")


def do_foo(x, y):
    print('foo', x, y)


def do_bar(s):
    print('bar', s)


if __name__ == '__main__':
    main()
